package proj2501.net_logo;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class NLButton extends JButton {
	private final NetLogo parent;
	private final String commandName;
	private String displayName;
	final boolean forever;
	private boolean isDown;
	private final boolean disableUntilTicksStart;
	public NLButton(NetLogo parent, String commandName, boolean forever, boolean disableUntilTicksStart) {
		this.parent = parent;
		this.commandName = commandName;
		displayName = commandName;
		setText(displayName);
		this.forever = forever;
		this.disableUntilTicksStart = disableUntilTicksStart;
		addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("NLButton \"" + displayName + "\" pressed.");
				if (NLButton.this.forever) {
					if (isDown) {
						setText(displayName);
						isDown = false;
					} else {
						setText(displayName + " (down)");
						isDown = true;
						runCommand();
					}
				} else {
					runCommand();
				}
			}
		});
	}
	void runCommand() {
		Runnable runnable = parent.commands.get(commandName);
		if (runnable == null) {
			System.out.println("Button clicked; but the command named \"" + commandName + "\" is not registered.");
		} else {
			if (forever) {
				double before = parent.ticks;
				runnable.run();
				if (before != parent.ticks) {
					if (parent.timer.isRunning()) {
						System.out.println("Tick timer already running, but it starts again now.");
					}
					parent.timer.start();
				}
			} else {
				runnable.run();
			}
		}
	}
}
